package com.byx.imserverutil.netty;

import com.byx.imserverutil.entity.MessageType;
import com.byx.imserverutil.entity.NettyChannel;
import com.byx.imserverutil.protobuf.ChatMessageProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * NettyWebSocketHandler
 *
 * @author Superb
 * @date 2021/2/9 13:47
 */
public class NettyWebSocketHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger=LoggerFactory.getLogger(NettyWebSocketHandler.class);

    private final NettyWebSocketImServiceImpl imService;

    public NettyWebSocketHandler(NettyWebSocketImServiceImpl imService) {
        this.imService = imService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.info(ctx.channel().remoteAddress() + "上线");
        logger.info("channelActive() ctx=" + ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.info(ctx.channel().remoteAddress() + "下线");
        logger.warn("channelInactive() ctx = " + ctx);
        NettyChannelContainer.getInstance().removeChannel(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg == null){
            return;
        }
        ChatMessageProtobuf.Msg message=(ChatMessageProtobuf.Msg)msg;
        logger.debug("channelRead() ctx = " + ctx + "\tmsg" + message);
        String fromId=message.getFromId();
        switch (message.getMessageType()){
            case MessageType.HAND_SHAKE_MSG:
                //保存用户id及通道
                NettyChannelContainer.getInstance().addChannel(new NettyChannel(fromId, ctx.channel()));
                logger.info("已保存通道："+ctx.channel()+"用户："+fromId);
                logger.info("通道中有："+NettyChannelContainer.getInstance().getAll());

                NettyChannelContainer.getInstance().getActiveChannel(fromId).getChannel().writeAndFlush(message);
                break;

            case MessageType.HEART_BEAT_MSG:
                NettyChannelContainer.getInstance().getActiveChannel(fromId).getChannel().writeAndFlush(message);
                break;

            case MessageType.SINGLE_CHAT_MSG:
                logger.info("正在发送单聊消息"+message);

                ChatMessageProtobuf.Msg statusReport = ChatMessageProtobuf.Msg.newBuilder()
                        .setMessageType(MessageType.SERVER_STATUS_REPORT)
                        .setMessageId(message.getMessageId())
                        .setTimestamp(System.currentTimeMillis())
                        .setStatusReport(1)
                        .build();
                NettyChannelContainer.getInstance().getActiveChannel(fromId).getChannel().writeAndFlush(statusReport);

                imService.sendMessage(message);
                break;
            case MessageType.GROUP_CHAT_MSG:
                logger.info("正在转发群聊消息"+message);

                ChatMessageProtobuf.Msg msgStatus = ChatMessageProtobuf.Msg.newBuilder()
                        .setMessageType(MessageType.SERVER_STATUS_REPORT)
                        .setMessageId(message.getMessageId())
                        .setTimestamp(System.currentTimeMillis())
                        .setStatusReport(1)
                        .build();
                NettyChannelContainer.getInstance().getActiveChannel(fromId).getChannel().writeAndFlush(msgStatus);
                imService.sendMessage(message);
                break;
            case MessageType.SYSTEM_MSG:
                break;
            default:break;
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        logger.error("exceptionCaught() ctx = " + ctx + "\tcause = " + cause);
    }
}
